package com.example.tianyutong.qanda.ui.question;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.http.HttpUtils;
import com.example.tianyutong.qanda.R;
import com.example.tianyutong.qanda.adapter.ListAdapter;
import com.example.tianyutong.qanda.app.ConstantsImageUrl;
import com.example.tianyutong.qanda.base.BaseActivity;
import com.example.tianyutong.qanda.base.BaseViewModel;
import com.example.tianyutong.qanda.bean.GankIoDataBean;
import com.example.tianyutong.qanda.bean.wanandroid.BaseResultBean;
import com.example.tianyutong.qanda.databinding.ActivityQuestionDetailBinding;
import com.example.tianyutong.qanda.http.HttpClient;
import com.example.tianyutong.qanda.ui.question.adapter.AnswerAdapter;
import com.example.tianyutong.qanda.utils.GlideUtil;
import com.example.tianyutong.qanda.utils.RefreshHelper;

import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.jingbin.library.ByRecyclerView;
import me.jingbin.library.decoration.SpacesItemDecoration;

public class QuestionDetailActivity extends BaseActivity<BaseViewModel, ActivityQuestionDetailBinding> implements View.OnClickListener {
    private long id;//问题id

    private int mPage = 1;
    private AnswerAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_question_detail);

        setTitle("详情");
        id = getIntent().getLongExtra("_id", 0);

        GlideUtil.displayCircle(bindingView.ivAvatar, ConstantsImageUrl.IC_AVATAR);

        bindingView.fabAdd.setOnClickListener(this);
        bindingView.ivLike.setOnClickListener(this);


        getDetail();

        initRecyclerView();

        showLoading();
        getAnswers();

        //是否收藏
        isCollected();

    }

    @Override
    protected void onResume() {
        super.onResume();
        mPage = 1;
        getAnswers();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fab_add:
                Intent intent = new Intent(this, AddAnswerActivity.class);
                intent.putExtra("_id", id);
                startActivity(intent);
                break;
            case R.id.iv_like:
                addLike();
                break;
        }
    }

    private void addLike() {
        HttpClient.Builder.getQAndAServer().addOrCancel(id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseResultBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(BaseResultBean bean) {
                        isCollected();
                        Toast.makeText(QuestionDetailActivity.this, bean.getErrorMsg(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    //获取详情
    private void getDetail() {
        HttpClient.Builder.getQAndAServer().getQuestionById(id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseResultBean<GankIoDataBean.ResultBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(BaseResultBean<GankIoDataBean.ResultBean> bean) {
                        showContentView();
                        if (bean.getErrorCode() == 0) {
                            GankIoDataBean.ResultBean data = bean.getData();
                            bindingView.tvTitle.setText(data.getTitle() + "a");
                            bindingView.tvContent.setText(data.getDesc());
                            bindingView.tvName.setText(data.getWho());
                            bindingView.tvDate.setText(data.getCreatedAt());
                        } else {
                            Toast.makeText(QuestionDetailActivity.this, bean.getErrorMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(QuestionDetailActivity.this, "请检查网络", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void getAnswers() {
        HttpClient.Builder.getQAndAServer().getAnswersByQuestionId(id, HttpUtils.per_page_more, mPage)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseResultBean<List<Answer>>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(BaseResultBean<List<Answer>> bean) {
                        showContentView();
                        if (bean != null && bean.getData() != null && bean.getData().size() > 0) {
                            if (mPage == 1) {
                                adapter.setNewData(bean.getData());
                            } else {
                                adapter.addData(bean.getData());
                            }
                            bindingView.recyclerView.loadMoreComplete();
                        } else {
                            if (mPage == 1) {
//                                showError();
                            } else {
                                bindingView.recyclerView.loadMoreEnd();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(QuestionDetailActivity.this, "请检查网络", Toast.LENGTH_SHORT).show();
                        if (mPage > 1) {
                            mPage--;
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void isCollected() {
        HttpClient.Builder.getQAndAServer().isCollection(id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseResultBean<Boolean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(BaseResultBean<Boolean> bean) {
                        if (bean.getErrorCode()==0){
                            if (bean.getData()) {
                                bindingView.ivLike.setImageResource(R.drawable.ic_collected);
                            } else {
                                bindingView.ivLike.setImageResource(R.drawable.ic_uncollect);
                            }
                        }else {
                            Toast.makeText(QuestionDetailActivity.this, bean.getErrorMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void initRecyclerView() {
        adapter = new AnswerAdapter();
        // 加了分割线，滚动条才会置顶
        SpacesItemDecoration itemDecoration = new SpacesItemDecoration(this, SpacesItemDecoration.VERTICAL, 1);
//        itemDecoration.setDrawable(R.drawable.shape_transparent);//就是全透明的一条线
        //xrvAndroid是fragment_android中ByRecyclerView的id名xrv_android
        RefreshHelper.initLinear(bindingView.recyclerView, true).addItemDecoration(itemDecoration);
        bindingView.recyclerView.setAdapter(adapter);
        bindingView.recyclerView.setOnRefreshListener(new ByRecyclerView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPage = 1;
                getAnswers();
            }
        });
        bindingView.recyclerView.setOnLoadMoreListener(new ByRecyclerView.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                mPage++;
                getAnswers();
            }
        }, 300);
    }

    /**
     * 加载失败后点击后的操作
     */
    @Override
    protected void onRefresh() {
        getDetail();
        mPage = 1;
        getAnswers();
    }
}
